package org.sean.framework.schedule;


import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.sean.framework.code.StatusCode;
import org.sean.framework.code.StatusInfo;
import org.sean.framework.exception.StatusException;
import org.sean.framework.logging.Logger;
import org.sean.framework.util.GSONUtil;
import org.sean.framework.util.NumberUtil;
import org.sean.framework.web.holder.RequestHolder;
import org.slf4j.MDC;

import java.util.Map;


/**
 * Created by linKe on 18/5/29.
 */

public class ScheduleUtils {
    //暂停任务
    public static final Integer STATUS_PAUSE = 1;
    /**
     * 任务调度参数key
     */
    public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY";
    public static final String JOB_HEADER_KEY = "JOB_HEADER_KEY";
    //key前缀
    private static final String JOB_NAME = "TASK_";

    private ScheduleUtils() {
    }

    /**
     * 获取触发器key
     *
     * @param jobId Job ID
     * @return Job TriggerKey
     */
    public static TriggerKey getTriggerKey(Integer jobId) {
        return TriggerKey.triggerKey(JOB_NAME + jobId);
    }

    /**
     * 获取jobKey
     *
     * @param jobId Job ID
     * @return Job Key
     */
    public static JobKey getJobKey(Integer jobId) {
        return JobKey.jobKey(JOB_NAME + jobId);
    }

    /**
     * 获取表达式触发器
     *
     * @param jobId     Job ID
     * @param scheduler Scheduler
     * @return CronTrigger
     */
    public static CronTrigger getCronTrigger(Scheduler scheduler, Integer jobId) {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            throw new StatusException(new StatusInfo(StatusCode.ERROR_UNKNOW).setAnyMessage("获取定时任务CronTrigger出现异常"), e);
        }
    }

    /**
     * 创建定时任务
     *
     * @param job       Job
     * @param scheduler Scheduler
     */
    public static void createScheduleJob(Scheduler scheduler, ScheduleJob job) {
        try {
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ScheduleJobRunnable.class).withIdentity(getJobKey(job.getId())
            ).build();
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();
            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(job.getId()))
                    .withSchedule(scheduleBuilder).build();
            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(JOB_PARAM_KEY, GSONUtil.obj2Json(job));
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new StatusException(new StatusInfo(StatusCode.ERROR_UNKNOW).setAnyMessage("创建定时任务失败"), e);
        }
    }

    /**
     * 更新定时任务
     *
     * @param job       Job
     * @param scheduler Scheduler
     */
    public static void updateScheduleJob(Scheduler scheduler, ScheduleJob job) {
        try {
            TriggerKey triggerKey = getTriggerKey(job.getId());
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();

            CronTrigger trigger = getCronTrigger(scheduler, job.getId());
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //参数
            trigger.getJobDataMap().put(JOB_PARAM_KEY, GSONUtil.obj2Json(job));
            scheduler.rescheduleJob(triggerKey, trigger);
            //暂停任务
            if (NumberUtil.equals(job.getStatus(), STATUS_PAUSE)) {
                pauseJob(scheduler, job.getId());
            }
        } catch (SchedulerException e) {
            throw new StatusException(new StatusInfo(StatusCode.ERROR_UNKNOW).setAnyMessage("更新定时任务失败"), e);
        }
    }

    /**
     * 立即执行任务,执行一次
     *
     * @param job       Job
     * @param scheduler Scheduler
     */
    public static void run(Scheduler scheduler, ScheduleJob job) {
        try {
            //参数
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(JOB_PARAM_KEY, GSONUtil.obj2Json(job));
            Map<String, String> headers = RequestHolder.getHeaders();
            if (headers.get(Logger.KEY_TRACE) == null) {
                headers.put(Logger.KEY_TRACE, MDC.get(Logger.KEY_TRACE));
            }
            if (headers.get(Logger.KEY_SPAN) == null) {
                headers.put(Logger.KEY_SPAN, MDC.get(Logger.KEY_SPAN));
            }
            dataMap.put(JOB_HEADER_KEY, headers);
            scheduler.triggerJob(getJobKey(job.getId()), dataMap);
        } catch (SchedulerException e) {
            throw new StatusException(new StatusInfo(StatusCode.ERROR_UNKNOW).setAnyMessage("立即执行定时任务失败"), e);
        }
    }

    /**
     * 暂停任务
     *
     * @param jobId     Job ID
     * @param scheduler Scheduler
     */
    public static void pauseJob(Scheduler scheduler, Integer jobId) {
        try {
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new StatusException(new StatusInfo(StatusCode.ERROR_UNKNOW).setAnyMessage("暂停定时任务失败"), e);
        }
    }

    /**
     * 恢复任务
     *
     * @param jobId     Job ID
     * @param scheduler Scheduler
     */
    public static void resumeJob(Scheduler scheduler, Integer jobId) {
        try {
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new StatusException(new StatusInfo(StatusCode.ERROR_UNKNOW).setAnyMessage("恢复定时任务失败"), e);
        }
    }

    /**
     * 删除定时任务
     *
     * @param jobId     Job ID
     * @param scheduler Scheduler
     */
    public static void deleteScheduleJob(Scheduler scheduler, Integer jobId) {
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new StatusException(new StatusInfo(StatusCode.ERROR_UNKNOW).setAnyMessage("删除定时任务失败"), e);
        }
    }
}
